const app = getApp()
const backgroundAudioManager = wx.getBackgroundAudioManager()
var requestApi = require('../../request/requestApi')
var util = require('../../utils/util.js');
var downloadTask=null;
var showModalStatus=false;
var stopTimerControl=false;
Page({
    data: {
        isIphoneX: false,
        screenWidth: '',
        screenHeight: '',
        rotateIndex: '',
        scrollTop:0,
        animationData: {}, //旋转使用
        animationLoadingData:{}, //loading 旋转使用
        loadingRoateIndex:'', //loading 旋转使用
        turnLoadingTimer:null,//loading 旋转使用
        isMoveIng: false,//是否正在旋转
        indexTimer:null,
        playBarControlWidthMax:540, //播放条长度
        playingIndex:0,//正在播放的曲目index
        playbarLength:0,//播放条长度
        playingMusicMaxLength:'--:--',//当前播放全部时间
        playingMusicMaxRecord:0,
        playingDuringTime:'0:00', //当前播放时间格式化
        playingDuringTimeRecord:0,
        isPause:false,
        networkSaveDataArray:[],
        networkFormatData:{},
        isLikeConnect:0,  // 是否在喜欢的请求中 1在请求中
        hasListened:0,   // 累计收听数
        isLimitByChange:0, //当从收藏跳转回来时 按钮无效 除非点击下一曲 (18117未使用需求改为回来时自动随机下一作品)
        isShowCardList:0, //是否显示收听数
        isPushMusicButton:false,
        isDragMusicButton:false,
        trunMusicTimer:null,
        trunMusicShakeTimer:null,
        isPlaying:false,
        timeIntervalCount:0,
        isOnSeeking:0, //是否正在跳转 0非 1是
        isOnSeekingArray:[], //跳转完成后 记录当前播放时间节点,如果连续5秒都是播放表示跳转失败从 5秒继续播放
        isOnSeekingType:null, //判断往前还是往后 pre,nxt
        seekingStartLength:0,
    },
    // 关闭上拉加载

    onReachBottom: function() {

        return

    },

    onLaunch: function () {

    },
    onLoad: function (option) {
        console.log( '-----------------index.js onLoad -----------')

        var that= this
        var workIdFromUrl = '';
        //查看请求workId
        console.log(option);
        if (typeof option.workId != 'undefined' && option.workId != '' && option.workId != undefined) {
            workIdFromUrl = option.workId;
        }
        if (workIdFromUrl ==''&&this.data.isPlaying==true){
            return;
        }
        // 创建动画
        this.animation = wx.createAnimation({
            duration: 500,
            timingFunction: "linear",
            success: function (res) {
                this.data.isMoveIng = false
            }
        })
        //设置基本参数
        app.globalData.isNeedChangePro=0;
        this.setData({
            isShowCard:this.data.isShowCardList,
            playingMusicMaxLength:this.data.playingMusicMaxLength
        })
        // 判断是否将小程序置于后台 二次进入时避免重新请求
        if (app.globalData.userId==1){
            this.showModal();
            //登陆
            this.connectToLoginFromNetwork(workIdFromUrl);
            //修改封面图宽高
            this.getSystemInfo();

        }else{
            //将页面以及数据重置
            this.initDataForNormal(1);
        }


    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {


    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log( '-----------------index.js 置于前台 -----------')
        console.log(app.globalData.playPage );

        if (app.globalData.playPage == "index"){
            //将页面以及数据重置
            this.initDataForNormal(1);
        } else{
            this.data.isLimitByChange=0;
            app.globalData.playPageProIndex=-1;
            this.musicPlayNextMenu();
        }
        if (app.globalData.userId!=1){
            this.configDataFromNetwork();
        }

    },

    onHide: function() {
        // Do something when hide.
        console.log( '-----------------index.js 置于后台 -----------')

    },
    //--------------------- 数据初始化 ---------------------
    //初始化数据 isNeedPlaying 当前需要播放  workdId作品id
    initData: function(workdId,isNeedPlaying) {
        // this.requestProMusicData(workdId,true);
        // 初始化数据 当前没有缓存数据 或 指定workid
        if (this.data.networkSaveDataArray.length<1 || workdId != ''){
            console.log('初始化数据 当前没有缓存数据 或 指定workid'+workdId)
            this.requestProMusicData(workdId,isNeedPlaying);
        }else{
            //从缓存数据中读取数据
            console.log('从缓存数据中读取数据')
            var showData = this.configInitDataToSaveData();
            this.configDataToPlayAndShowData(showData);
        }

    },
    /**
     *  请求作品数据 并保存在 数组中
     */
    requestProMusicData: function(workId,isNeedPlaying){
        var that = this;
        // workId=27186;
        requestApi.kukeGetRandomWork(workId).then(res=>{
            //格式化数据
            var formatData=util.formatNetworkMusicData(res);
            //缓存数据 并保存 以及提出
            var showData = that.configInitDataToSaveData(workId,formatData);
            if (isNeedPlaying) {
                that.data.isMoveIng = false;
                that.configDataToPlayAndShowData(showData);
            }
        })
    },
    // 缓存数据处理 并保存 以及提出
    configInitDataToSaveData: function(workId,res){
        var that = this
        var playData={};
        // 仅切换作品
        if (typeof res != 'undefined'&&res!=''){
            this.data.networkSaveDataArray.push(res);

        }
        //提出数据 如果workId不为空或者数组小于1 则用现有数据
        if (workId != ''&&typeof workId != 'undefined'){
            playData=res;
        }else{
            //使用缓存的数据
            playData=this.data.networkSaveDataArray[0];

        }
        //继续缓存数据 去请求数据
        if (this.data.networkSaveDataArray.length<=10){
            console.log('缓存数据为'+this.data.networkSaveDataArray.length+'继续缓存')
            setTimeout(function () {
                that.requestProMusicData();
            },500)

        }else{
            this.data.networkSaveDataArray.splice(0,1);
        }
        /**
         * 下载图片使用代码 因大量占用资源 暂不使用
         * @type {Array}
         */
        // if(this.data.networkSaveDataArray.length>0){
        //     if (downloadTask!=null){
        //         downloadTask.abort();// 取消下载任务
        //         downloadTask=null;
        //     }
        //
        //
        //     this.configCacheProMusicImage();
        // }


        app.globalData.indexSaveNetworkData=this.data.networkSaveDataArray;
        return playData;
    },
    /**
     * 下载图片使用代码 因大量占用资源 暂不使用
     * @type {Array}
     */
    configCacheProMusicImage:function(length){
        var isNeedDownLoadInex = -1;
        for (let i = 0; i < this.data.networkSaveDataArray.length ; i++) {
            let singData = this.data.networkSaveDataArray[i];
            if (typeof singData.downImg == "undefined") {
                // this.data.networkSaveDataArray[i].downImg ='';
                isNeedDownLoadInex = i;
                break;
            }
        }
        if (isNeedDownLoadInex == -1){
            return;
        }
        if (downloadTask!=null){
            return;
        }
        // if (app.globalData.isOnBackApplication==true){
        //     // downloadTask.abort();// 取消下载任务
        //     downloadTask=null;
        //     return
        // }
        var _this = this;
        // console.log('downloadTask',downloadTask);
        downloadTask=wx.downloadFile({
            url: this.data.networkSaveDataArray[isNeedDownLoadInex].mp3Img, //仅为示例，并非真实的资源
            success: function (res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                // console.log(res);
                downloadTask=null;
                _this.data.networkSaveDataArray[isNeedDownLoadInex].downImg=res.tempFilePath;
                _this.configCacheProMusicImage();

            }
        })
        downloadTask.onProgressUpdate((res) => {
            // console.log(this.data.networkSaveDataArray[isNeedDownLoadInex].mp3Img,'下载进度', res.progress)
            // console.log('已经下载的数据长度', res.totalBytesWritten)
            // console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
        })
    },
    configDataToPlayAndShowData:function(res){

        this.data.networkFormatData=res;
        app.globalData.indexNetworkData=this.data.networkFormatData;
        this.initDataForNormal(0);
    },

    // 数据请求后初始化数据 0 新数据需重新播放 1旧数据继续播放
    initDataForNormal:function(iscContinue){
        var that = this;
        that.data.networkFormatData = app.globalData.indexNetworkData;
        app.globalData.playList = that.data.networkFormatData.mp3List;
        this.data.networkSaveDataArray=app.globalData.indexSaveNetworkData;

        that.setData({
            networkFormatData: that.data.networkFormatData,
        })
        if (iscContinue==0){
            that.musicPlay(1);
        }

        this.setIndexTimerState('run');
        that.timerController();
    },
    //--------------------- 播放心跳 ---------------------
    timerController: function(){
        this.data.timeIntervalCount++;
        if (this.data.timeIntervalCount>1){
            return;
        }
        var that = this;
        that.data.indexTimer = setInterval(function () {
            try {
                //时间更新 判断是否已经需要切换下一个作品
                that.setChangeProOnUpdate();

                if (app.globalData.appIsOnShow==false){
                    console.log('-----------index.js  timer    后台---------')
                    // setTimeout(that.timerController(),0);
                    return;
                }else{
                    //判断是否在favor业
                    that.judgeIsOnOtherPage();
                    // 判断您是否正在跳转中 如果跳转中则不再更新进度条与时间因跳转音乐会先到1再开始调整
                    if (that.seekJudgeIsError()){
                        //时间更新 更新进度条
                        that.setProcessBarOnUpdate();
                        //时间更新 更新页面当前播放时间
                        that.setChangeMusicDuringText();
                    }
                    //时间更新 更新总时间
                    that.setMaxLengthOnUpdate();
                    //时间更新 根据index切换播放章节
                    that.setChangeSongOnUpdate();

                    // if (stopTimerControl==false){
                    //     setTimeout(that.timerController(),0);
                    // }else{
                    //     console.log('-----------关闭index.js  timer---------')
                    // }
                }


            } catch (e) { }
        }, 500)
    },
//--------------------- 时间更新方法 ---------------------
    //时间更新 更新进度条
    setProcessBarOnUpdate:function(){
        var that = this;
        //当前时间
        var currentPosition = Math.ceil(app.globalData.playMusicCurrentLength )
        console.log( 'i播放进度 '+currentPosition)
        //总时间
        var duration = Math.ceil(backgroundAudioManager.duration )
        // console.log('总时长'+duration)

        if (typeof  currentPosition != 'undefined'&&currentPosition != 0&&duration!=0&&typeof duration!= 'undefined'){

            //根据播放进度 设置播放按钮动画
            var singL= that.data.playBarControlWidthMax/(duration);
            var newPosition=singL*currentPosition;
            if (newPosition!=that.data.playbarLength) {
                that.data.playbarLength=newPosition;
                that.setData({
                    playbarLength:that.data.playbarLength
                })
            }

        }

    },
    seekJudgeIsError:function(){
        var currentPosition = Math.ceil(app.globalData.playMusicCurrentLength )
        if (this.data.isOnSeeking==1||currentPosition==1){
            // if (&&currentPosition<this.data.playingDuringTimeRecord)
            this.data.isOnSeekingArray.push(currentPosition);
            console.log('正在跳转计时 当前播放时间',currentPosition);
            if (this.data.isOnSeekingArray.length%6==0||currentPosition==this.data.playingMusicMaxRecord){
                console.log('跳转出错 下一秒从正在播放跳转开始播放');
                this.data.isOnSeeking=0;
                this.data.isOnSeekingArray=[];
                this.data.isOnSeekingType=null;
            }
            return false;
        }
        this.data.isOnSeekingArray=[];
        this.data.isOnSeeking=0;
        this.data.isOnSeekingType=null;
        return true;

    },
    //时间更新 更新页面当前播放时间
    setChangeMusicDuringText:function(){
        var that = this;
        //当前时间
        var currentPosition = Math.ceil(app.globalData.playMusicCurrentLength )
        var appCurrentPosition = Math.ceil(backgroundAudioManager.currentTime )
        if (typeof  currentPosition != 'undefined' && currentPosition != 0 &&!isNaN(currentPosition)){
            // console.log(currentPosition);
            //判断是否在跳转中 进度条回退到0

            var newDuringTime=util.secToTimefunction(appCurrentPosition)
            if (that.data.playingDuringTime!=newDuringTime) {
                that.data.playingDuringTime = newDuringTime;
                that.data.playingDuringTimeRecord=currentPosition;
                that.setData({
                    playingDuringTime:newDuringTime
                })
            }

        }
    },
    //时间更新 更新总时间
    setMaxLengthOnUpdate: function(){
        var that = this;
        //总时间
        var duration = Math.ceil(backgroundAudioManager.duration )

        if (typeof  duration != 'undefined' && duration != 0 &&!isNaN(duration)&&duration!=0){
            //&&typeof duration!='undefined'&&that.data.playingMusicMaxLength=='--:--'
            // console.log(duration);
            var newPlayingMusicMaxLength = util.secToTimefunction(duration);
            that.data.playingMusicMaxRecord = duration;
            if (newPlayingMusicMaxLength!=that.data.playingMusicMaxLength&&duration>0) {
                that.setData({
                    playingMusicMaxLength:newPlayingMusicMaxLength
                })
            }

        }
    },
    //时间更新 根据index切换播放章节
    setChangeSongOnUpdate:function(){
        var that = this;
        //如果切换歌曲 切换选中状态
        if (app.globalData.playMusicIndex != that.data.playingIndex){
            that.data.playingIndex = app.globalData.playMusicIndex;
            that.setData({
                playingIndex:that.data.playingIndex
            })
        }
        if (this.data.hasListened!=app.globalData.hasListened) {
            that.setData({
                hasListened:app.globalData.hasListened
            })
        }

    },
    //时间更新 判断是否已经需要切换下一个作品
    setChangeProOnUpdate:function(){
        var that = this;
        //切换下一曲
        if (app.globalData.isNeedChangePro  == 1 && app.globalData.playPage=='index'){
            console.log('接受并切换下一首');
            that.musicPlayNextMenu();
        }
    },

    //--------------------- 喜欢控制 ---------------------
    //点击喜欢按钮
    clickLikeMusic: function (){
        if (this.data.isLikeConnect==0){
            this.data.isLikeConnect=1;
            var that = this
            if(this.data.networkFormatData.isLike == 0){
                this.data.networkFormatData.isLike = 1
            }else{
                this.data.networkFormatData.isLike = 0;
            }
            requestApi.kukeSetFavoriteCollect(this.data.networkFormatData.itemcode,this.data.networkFormatData.workId,this.data.networkFormatData.isLike).then(res=>{
                console.log('是否喜欢-----------------')
                app.globalData.indexNetworkData=that.data.networkFormatData;
                that.setData({
                    networkFormatData: that.data.networkFormatData
                })
                that.data.isLikeConnect =0;
            })

        }


    },
    //--------------------- 歌单列表控制 ---------------------
    //点击歌单列表
    clickMusicList: function (e){
        if (this.data.isLimitByChange==1){
            return;
        }
        if (e.currentTarget.dataset.index != this.data.playingIndex) {
            console.log(e.currentTarget.dataset.index);
            this.data.playingIndex = e.currentTarget.dataset.index;
            app.globalData.playMusicIndex = e.currentTarget.dataset.index;
            this.data.playbarLength = 0;
            this.data.playingDuringTime='0:00';
            this.data.playingMusicMaxLength='--:--';
            this.data.isOnSeeking=0;
            this.data.isOnSeekingType=null
            this.setData({
                playingIndex:this.data.playingIndex,
                playbarLength: this.data.playbarLength,
                playingDuringTime: this.data.playingDuringTime,
                playingMusicMaxLength:this.data.playingMusicMaxLength,
            })
            this.musicPlay();
        }

    },
    //--------------------- 播放暂停控制 ---------------------
    //点击播放或暂停
    clickToPlayOrPause: function (e) {
        if (this.data.isLimitByChange==1||this.data.isOnSeeking==1||!this.data.playingMusicMaxRecord>0){
            return;
        }
        //todo 外部暂定会闪烁
        var isPause = backgroundAudioManager.paused;
        console.log('点击播放或暂停 backgroundAudioManager'+isPause);
        console.log('点击播放或暂停 this'+this.data.isPause);
        this.data.isPause=isPause;
        this.setData({
            isPause:this.data.isPause
        })
        if (typeof isPause == 'undefined'|| isPause==true){

            //当前时间
            var currentPosition = Math.ceil(app.globalData.playMusicCurrentLength );

            console.log('外部点击暂停 暂停时间 '+currentPosition);

            app.musicControllerForPause(currentPosition);
        }else if(isPause == false) {
            backgroundAudioManager.pause();
            app.globalData.isPlaying=false;
        }
        // this.data.isPause = !this.data.isPause;

    },
    //判断是否需要 暂停 pause 或者 播放 play
    setPauseState: function(stateType){
        if (stateType == 'play'){
            // this.data.isPause = false;
            this.setIndexTimerState('run');
            this.timerController();
        }else{
            this.data.isPause = true;
            backgroundAudioManager.pause();
            this.setIndexTimerState('stop');
        }
        this.setData({
            isPause:this.data.isPause
        })
    },

    //--------------------- 进度条控制 ---------------------
    touchProcessStart: function (e) {
        if (this.data.isLimitByChange==1||!this.data.playingMusicMaxRecord>0){
            return;
        }
        if (e.touches.length == 1) {
            this.setPauseState('pause');

            // this.setData({
            //     //设置触摸起始点水平方向位置
            //     startX: e.touches[0].clientX
            // });
            this.data.seekingStartLength=this.data.playbarLength;
        }
    },
    touchProcessMove: function (e) {
        if (this.data.isLimitByChange==1||!this.data.playingMusicMaxRecord>0){
            return;
        }
        var that = this
        if (e.touches.length == 1) {
            var newPlayBarLength;
            //手指移动时水平方向位置
            var moveX = e.touches[0].clientX;
            // console.log(e);
            //手指起始点位置与移动期间的差值
            var disX = moveX;
            //
            //     var txtStyle = "";
            if (disX == 0 || disX < 0){
                newPlayBarLength=1;
            } else if (disX >  that.data.playBarControlWidthMax) {
                newPlayBarLength= that.data.playBarControlWidthMax;
            }else{
                newPlayBarLength=disX*1.68;
            }
            if (newPlayBarLength >  that.data.playBarControlWidthMax) {
                newPlayBarLength =  that.data.playBarControlWidthMax;
            }
            console.log(newPlayBarLength);
            var singL =  that.data.playBarControlWidthMax / (this.data.playingMusicMaxRecord);
            // console.log('singL'+this.data.playingMusicMaxLength)
            var newPlayingDuringTime=util.secToTimefunction(Math.ceil(newPlayBarLength /singL));
            if (newPlayBarLength!= this.data.playbarLength) {

                that.setData({
                    playbarLength: newPlayBarLength,

                });
            }
            if (newPlayingDuringTime!=this.data.playingDuringTime) {
                that.setData({
                    playingDuringTime: newPlayingDuringTime,
                });
            }


        }
    },
    touchProcessEnd: function (e) {
        if (this.data.isLimitByChange==1||!this.data.playingMusicMaxRecord>0){
            return;
        }
        var that = this;
        if (e.changedTouches.length == 1) {

            that.setPauseState('play');
            //根据播放进度 设置播放按钮动画
            var singL =  that.data.playBarControlWidthMax / (app.globalData.playMusicLength);
            app.globalData.playMusicCurrentLength = that.data.playbarLength /singL;
            // backgroundAudioManager.seek(Math.ceil(app.globalData.playMusicLength))

            if ( app.globalData.playMusicCurrentLength>=app.globalData.playMusicLength){
                this.data.isOnSeeking=0;
                this.data.isOnSeekingType=null;
            }else if (this.data.seekingStartLength>=this.data.playbarLength) {
                this.data.isOnSeeking=1;
                this.data.isOnSeekingType='pre';
            }else if(this.data.seekingStartLength<this.data.playbarLength){
                this.data.isOnSeeking=1;
                this.data.isOnSeekingType='next';
            }
            that.data.playingDuringTimeRecord=app.globalData.playMusicCurrentLength;
            app.musicControllerForPause(Math.ceil(app.globalData.playMusicCurrentLength));


        }
    },
    clickProcessMain: function (e){
        if (this.data.isLimitByChange==1){
            return;
        }
        var that = this;
        console.log(e.changedTouches[0].clientX);
        var distX = e.changedTouches[0].clientX*1.68;
        if (distX >  that.data.playBarControlWidthMax){
            distX =  that.data.playBarControlWidthMax
        } else if(distX<0){
            distX = 0;
        }
        that.data.playbarLength = distX;
        that.setPauseState();
        var duration = Math.ceil(backgroundAudioManager.duration );
        var singL =  that.data.playBarControlWidthMax / (duration-1);
        app.globalData.playMusicLength = that.data.playbarLength /singL;
        backgroundAudioManager.seek(Math.ceil(app.globalData.playMusicLength));

    },

    //--------------------- 跳转控制 ---------------------
    clickToNavigation: function (e){
        console.log(e.currentTarget.dataset.type)  ;
        // this.musicStop;
        if (e.currentTarget.dataset.type == 'cardList'){
            wx.navigateTo({
                //保留当前页面，跳转到应用内的某个页面（最多打开5个页面，之后按钮就没有响应的）
                url:"/pages/cardList/cardList"
            })
        }
        if (e.currentTarget.dataset.type == 'favor'){
            wx.navigateTo({
                //保留当前页面，跳转到应用内的某个页面（最多打开5个页面，之后按钮就没有响应的）
                url:"/pages/favor/favor"
            })
        }
    },
    judgeIsOnOtherPage:function(){
        if (app.globalData.playPage !='index'){
            this.data.isLimitByChange=1;
            this.data.isPause=true;

            this.setIndexTimerState('stop');
            this.setData({
                isPause:this.data.isPause,
                playbarLength:0,
                playingDuringTime: '0:00',
            })
        }else{
            var isPauseManager = backgroundAudioManager.paused;
            if (typeof isPauseManager == 'undefined'){
                console.log('未开始播放 error')
                return;
            }
            if (isPauseManager!=this.data.isPause) {
                this.data.isPause= isPauseManager;
                this.setData({
                    isPause:this.data.isPause
                })
            }


        }

    },
    musicPlay: function () {
        console.log('正在播放作品名称----------------------')
        console.log(this.data.networkFormatData.mp3Title);
        app.musicControllerForState(0);
    },

    musicPlayNextMenu: function (){
        app.globalData.playPage='index';
        this.resetMusicNormalSetting();
        // this.setIndexTimerState('stop');
        this.initData('',true);
    },
    resetMusicNormalSetting: function (){
        this.changeToScrollToTop();
        app.globalData.playMusicIndex=0;
        app.globalData.playMusicLength=0;
        app.globalData.isNeedChangePro=0;
        this.data.isPause=false;
        this.data.playingDuringTime='0:00';
        this.data.playingMusicMaxLength='--:--';
        this.data.isOnSeeking=0;
        this.data.isOnSeekingType=null;
        this.data.playingMusicMaxRecord=0;
        this.setData({
            isPause:this.data.isPause,
            playbarLength:0,
            playingMusicMaxLength:this.data.playingMusicMaxLength,
            playingDuringTime:this.data.playingDuringTime,
        })

    },


    //--------------------- 按钮转动 ---------------------
    touchAudioStart: function (e) {
        var that = this
        app.globalData.playPageProIndex=-1;
        app.globalData.playPage = "index";

        if(that.data.isPushMusicButton != true){
            that.data.trunMusicTimer = setInterval(function () {
                that.data.isPushMusicButton = true;
                that.data.rotateIndex++;
                that.animation.rotate(5 * (that.data.rotateIndex)).step();
                that.setData({
                    animationData: that.animation.export()
                })
            }, 20)
            that.data.trunMusicShakeTimer = setInterval(function () {
                wx.vibrateShort();
            }, 50)

        }

    },
    // 触摸移动事件
    touchAudioMove: function (e) {

    },
    touchAudioEnd: function (e){
        console.log('-----------touchAudioEnd----------')
        clearInterval( this.data.trunMusicTimer);
        clearInterval( this.data.trunMusicShakeTimer);
        if (this.data.isPushMusicButton == true || this.data.isDragMusicButton == true){
            this.data.isLimitByChange=0;

            this.musicPlayNextMenu();
        }
        this.data.isPushMusicButton = false;
        this.data.isDragMusicButton = false;

    },

    //--------------------- 列表滑动 ---------------------
    changeToScrollToTop: function () {
        this.data.scrollTop=0;
        this.setData({
            scrollTop:this.data.scrollTop
        })


    },
    changeToScrollToTop: function () {
        this.data.scrollTop=0;
        this.setData({
            scrollTop:this.data.scrollTop
        })


    },
//--------------------- 网络请求 ---------------------
    configDataFromNetwork:function () {
        var that = this;
        requestApi.kukeGetCardList(1,10).then(res =>{
            that.hideModal();
            console.log('kukeGetCardList-----------------')
            console.log(res)
            that.data.list = res.data.data
            var listNetData = res.data.data;
            if (listNetData.length>0){
                that.data.isShowCardList =1;
            }else{
                that.data.isShowCardList =0;
            }
            that.setData({
                isShowCard:that.data.isShowCardList
            })
        })

    },
    connectToLoginFromNetwork:function (workIdFromUrl) {
        var that = this
        var wxLogin = requestApi.wxLogin();
        wxLogin().then(res => {
            console.log('wx.login-----------------success')
            // 服务器 登陆
            return requestApi.kukeLoginToServer(res.code)
        }).then(res => {
            console.log('server.login-----------------success')
            app.globalData.userId = res.data.data.id;
        }).finally(function (res) {
            console.log('finally~')
            app.globalData.playPage ='index';
            that.initData(workIdFromUrl,true);
            that.configDataFromNetwork();
            that.data.isPlaying=true;
        })

    },
    getSystemInfo:function () {
        var that = this
        var wxetSystemInfo = requestApi.wxGetSystemInfo();
        wxetSystemInfo().then(res =>{
            var windowWidth = res.windowWidth;
            var windowHeight = res.windowHeight;
            if (util.systemInfoToPhoneHeightIsX(res)=='X') {
                that.setData({
                    isIphoneX: true,
                })
            } else if(util.systemInfoToPhoneHeightIsX(res)=='N'){
                that.setData({
                    isIphoneX: false,
                })
            }
            that.setData({
                screenWidth: windowWidth,
                screenHeight: windowHeight,
            })
        })
    },
    //--------------------- 分享控制 ---------------------
    onShareAppMessage: function( options ){
        var that = this;
        // 设置菜单中的转发按钮触发转发事件时的转发内容
        var shareObj = {
            title: that.data.networkFormatData.mp3Title,        // 默认是小程序的名称(可以写slogan等)
            path:  '/pages/index/index?workId='+this.data.networkFormatData.workId,        // 默认是当前页面，必须是以‘/’开头的完整路径
            imageUrl: that.data.networkFormatData.mp3Img,     //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
            success: function(res){
                // 转发成功之后的回调
                if(res.errMsg == 'shareAppMessage:ok'){
                    console.log('转发成功之后的回调');
                    console.log(res)
                }
            },
            fail: function(res){
                // 转发失败之后的回调
                if(res.errMsg == 'shareAppMessage:fail cancel'){
                    console.log('用户取消转发');
                    console.log(res)
                    // 用户取消转发
                }else if(res.errMsg == 'shareAppMessage:fail'){
                    // 转发失败，其中 detail message 为详细失败信息
                    console.log('转发失败');
                    console.log(res)
                }
            },
        }
        // 来自页面内的按钮的转发
        if( options.from == 'button' ){
            var eData = options.target.dataset;
            console.log('来自页面内的按钮的转发');
            console.log( eData.name );     // shareBtn
            // 此处可以修改 shareObj 中的内容
            shareObj.path = '/pages/index/index?workId='+this.data.networkFormatData.workId;
        }
        // 返回shareObj
        return shareObj;
    },
    //--------------------- 遮罩控制 ---------------------
    showModal: function () {
        var that = this
        // 显示遮罩层
        this.data.turnLoadingTimer = setInterval(function () {
            that.data.loadingRoateIndex++;
            that.animation.rotate(5 * (that.data.loadingRoateIndex)).step();
            that.setData({
                animationLoadingData: that.animation.export()
            })
        }, 20)
        this.setData({
            showModalStatus: true
        })

    },
    hideModal: function () {
        clearInterval(this.data.turnLoadingTimer);
        this.setData({
            showModalStatus: false
        })

    },
    //--------------------- 其他控制 ---------------------
    //关闭或者开启 indexTimer state:run  || stop
    setIndexTimerState:function(state){
        clearInterval(this.data.indexTimer);
        this.data.timeIntervalCount=0;
        if(state=='run'){

            stopTimerControl=false;
            this.data.indexTimer=null;
        }else if (state=='stop') {

            stopTimerControl=true;
            this.data.indexTimer=null;
        }
    },
    //图片读取错误
    imageLoadingError:function () {
        this.data.networkFormatData.downImg=this.data.networkFormatData.mp3Img;
        this.setData({
            networkFormatData:this.data.networkFormatData
        })
    }
})
